package com.pdd.mall.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.MerchantLoginParam;
import com.pdd.mall.dto.ProductParam;
import com.pdd.mall.dto.PromotionParam;
import com.pdd.mall.dto.StatisticsDataDTO;
import com.pdd.mall.dto.UpdatePasswordParam;
import com.pdd.mall.dto.UserAnalysisDTO;
import com.pdd.mall.entity.Merchant;
import com.pdd.mall.entity.Product;
import com.pdd.mall.entity.Promotion;
import com.pdd.mall.service.MerchantService;
import com.pdd.mall.service.ProductService;
import com.pdd.mall.service.PromotionService;
import com.pdd.mall.service.StatisticsService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家控制器
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private ProductService productService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private StatisticsService statisticsService;

    @PostMapping("/login")
    public CommonResult<Map<String, String>> login(@RequestBody @Valid MerchantLoginParam param) {
        String token = merchantService.login(param);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return CommonResult.success(tokenMap);
    }

    @GetMapping("/info")
    public CommonResult<Merchant> getMerchantInfo() {
        String username = getCurrentUsername();
        Merchant merchant = merchantService.getMerchantInfo(username);
        if (merchant == null) {
            return CommonResult.unauthorized("未登录或登录已过期");
        }
        // 不返回密码
        merchant.setPassword(null);
        return CommonResult.success(merchant);
    }

    @PostMapping("/updatePassword")
    public CommonResult<String> updatePassword(@RequestBody @Valid UpdatePasswordParam param) {
        String username = getCurrentUsername();
        boolean success = merchantService.updatePassword(username, param);
        if (success) {
            return CommonResult.success("密码修改成功");
        } else {
            return CommonResult.validateFailed("旧密码错误");
        }
    }

    /**
     * 商品管理相关接口
     */
    @GetMapping("/products")
    public CommonResult<Page<Product>> getProductList(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sortField", required = false) String sortField,
            @RequestParam(value = "sortOrder", required = false) String sortOrder) {
        System.out.println("获取商品列表请求 - 参数: keyword=" + keyword + ", categoryId=" + categoryId +
                          ", status=" + status + ", pageNum=" + pageNum + ", pageSize=" + pageSize +
                          ", sortField=" + sortField + ", sortOrder=" + sortOrder);

        Long merchantId = getCurrentMerchantId();
        if (merchantId == null) {
            System.err.println("无法获取商家ID，返回空列表");
            return CommonResult.unauthorized("未登录或登录已过期");
        }

        System.out.println("查询商家ID: " + merchantId + " 的商品");
        Page<Product> productList = productService.getMerchantProductList(merchantId, keyword, categoryId, status, pageNum, pageSize, sortField, sortOrder);

        System.out.println("查询结果: 总记录数=" + productList.getTotal() + ", 当前页记录数=" + productList.getRecords().size());
        return CommonResult.success(productList);
    }

    @GetMapping("/products/{id}")
    public CommonResult<Product> getProductDetail(@PathVariable Long id) {
        Long merchantId = getCurrentMerchantId();
        Product product = productService.getMerchantProductDetail(id, merchantId);
        if (product == null) {
            return CommonResult.notFound("商品不存在");
        }
        return CommonResult.success(product);
    }

    @PostMapping("/products")
    public CommonResult<Product> addProduct(@RequestBody @Valid ProductParam param) {
        Long merchantId = getCurrentMerchantId();
        Product product = productService.addProduct(param, merchantId);
        return CommonResult.success(product);
    }

    @PutMapping("/products/{id}")
    public CommonResult<Product> updateProduct(@PathVariable Long id, @RequestBody @Valid ProductParam param) {
        Long merchantId = getCurrentMerchantId();
        Product product = productService.updateProduct(id, param, merchantId);
        if (product == null) {
            return CommonResult.notFound("商品不存在");
        }
        return CommonResult.success(product);
    }

    @DeleteMapping("/products/{id}")
    public CommonResult<String> deleteProduct(@PathVariable Long id) {
        Long merchantId = getCurrentMerchantId();
        boolean success = productService.deleteProduct(id, merchantId);
        if (success) {
            return CommonResult.success(null);
        } else {
            return CommonResult.notFound("商品不存在");
        }
    }

    @PutMapping("/products/{id}/status")
    public CommonResult<String> updateProductStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        Long merchantId = getCurrentMerchantId();
        boolean success = productService.updateProductStatus(id, status, merchantId);
        if (success) {
            return CommonResult.success(null);
        } else {
            return CommonResult.notFound("商品不存在");
        }
    }

    /**
     * 促销活动管理相关接口
     */
    @GetMapping("/promotions")
    public CommonResult<Page<Promotion>> getPromotionList(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        System.out.println("获取促销活动列表请求 - 参数: keyword=" + keyword + ", type=" + type +
                          ", status=" + status + ", startTime=" + startTime + ", endTime=" + endTime +
                          ", pageNum=" + pageNum + ", pageSize=" + pageSize);

        Long merchantId = getCurrentMerchantId();
        if (merchantId == null) {
            System.err.println("无法获取商家ID，返回空列表");
            return CommonResult.unauthorized("未登录或登录已过期");
        }

        System.out.println("查询商家ID: " + merchantId + " 的促销活动");
        Page<Promotion> promotionList = promotionService.getPromotionList(merchantId, keyword, type, status, startTime, endTime, pageNum, pageSize);

        System.out.println("查询结果: 总记录数=" + promotionList.getTotal() + ", 当前页记录数=" + promotionList.getRecords().size());
        return CommonResult.success(promotionList);
    }

    @GetMapping("/promotions/{id}")
    public CommonResult<Map<String, Object>> getPromotionDetail(@PathVariable Long id) {
        Long merchantId = getCurrentMerchantId();
        Promotion promotion = promotionService.getPromotionDetail(id, merchantId);
        if (promotion == null) {
            return CommonResult.notFound("促销活动不存在");
        }

        List<Long> productIds = promotionService.getPromotionProductIds(id);

        Map<String, Object> result = new HashMap<>();
        result.put("promotion", promotion);
        result.put("productIds", productIds);

        return CommonResult.success(result);
    }

    @PostMapping("/promotions")
    public CommonResult<Promotion> addPromotion(@RequestBody @Valid PromotionParam param) {
        Long merchantId = getCurrentMerchantId();
        Promotion promotion = promotionService.addPromotion(param, merchantId);
        return CommonResult.success(promotion);
    }

    @PutMapping("/promotions/{id}")
    public CommonResult<Promotion> updatePromotion(@PathVariable Long id, @RequestBody @Valid PromotionParam param) {
        Long merchantId = getCurrentMerchantId();
        Promotion promotion = promotionService.updatePromotion(id, param, merchantId);
        if (promotion == null) {
            return CommonResult.notFound("促销活动不存在");
        }
        return CommonResult.success(promotion);
    }

    @DeleteMapping("/promotions/{id}")
    public CommonResult<String> deletePromotion(@PathVariable Long id) {
        Long merchantId = getCurrentMerchantId();
        boolean success = promotionService.deletePromotion(id, merchantId);
        if (success) {
            return CommonResult.success(null);
        } else {
            return CommonResult.notFound("促销活动不存在");
        }
    }

    @PutMapping("/promotions/{id}/status")
    public CommonResult<String> updatePromotionStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        Long merchantId = getCurrentMerchantId();
        boolean success = promotionService.updatePromotionStatus(id, status, merchantId);
        if (success) {
            // 如果状态更新成功，根据状态更新商品价格
            if (status == 1) { // 1-进行中
                // 促销活动开始，更新商品价格为促销价格
                int updatedCount = promotionService.updateProductPricesByPromotion(id, true);
                System.out.println("促销活动开始，更新了 " + updatedCount + " 个商品的价格");
                return CommonResult.success("促销活动已开始，已更新 " + updatedCount + " 个商品的价格");
            } else if (status == 2 || status == 3) { // 2-已结束，3-已取消
                // 促销活动结束，恢复商品原价
                int updatedCount = promotionService.updateProductPricesByPromotion(id, false);
                System.out.println("促销活动结束，恢复了 " + updatedCount + " 个商品的原价");
                return CommonResult.success("促销活动已" + (status == 2 ? "结束" : "取消") + "，已恢复 " + updatedCount + " 个商品的原价");
            }
            return CommonResult.success(null);
        } else {
            return CommonResult.notFound("促销活动不存在");
        }
    }

    /**
     * 经营数据相关接口
     */
    @GetMapping("/statistics")
    public CommonResult<StatisticsDataDTO> getStatistics() {
        Long merchantId = getCurrentMerchantId();
        StatisticsDataDTO statisticsData = statisticsService.getMerchantStatistics(merchantId);
        return CommonResult.success(statisticsData);
    }

    /**
     * 用户分析相关接口
     */
    @GetMapping("/users/analysis")
    public CommonResult<UserAnalysisDTO> getUserAnalysis() {
        Long merchantId = getCurrentMerchantId();
        UserAnalysisDTO userAnalysis = statisticsService.getUserAnalysis(merchantId);
        return CommonResult.success(userAnalysis);
    }

    /**
     * 获取当前登录用户名
     */
    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getName();
    }

    /**
     * 获取当前商家ID
     */
    private Long getCurrentMerchantId() {
        String username = getCurrentUsername();
        System.out.println("当前登录的商家用户名: " + username);

        Merchant merchant = merchantService.getMerchantByUsername(username);
        if (merchant == null) {
            System.err.println("无法获取商家信息，用户名: " + username);
            return null;
        }

        System.out.println("获取到商家ID: " + merchant.getId());
        return merchant.getId();
    }
}
